<?php

/**
 * @author chenshubo
 * 维尼供应商
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Model\CommodityModel\SupplierCommodity;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\ShopWeiNi\ShopWeiNiApiClient;

class Shopweini extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //下单商品重组
        $supplierGoodsInfo  = $param['supplierGoodsInfo'];
        $apiBody            = $supplierGoodsInfo['apiBody'];
        $userGoodsList      = $supplierGoodsInfo['userGoodsList'];
        $goodsList          = $supplierGoodsInfo['goodsList'];
        $orderItems = [];

        //根据defaultStock分组
        $defaultStockGroupGoodsList = [];
        foreach ($goodsList as $item ) {
            $index_key = $item['defaultStock']."_".$item['deliveryMethod'];
            $defaultStockGroupGoodsList[$index_key][] = $item;
            unset($item);
        }

        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;

        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;

        //按照上游仓库进行拆单
        foreach ($defaultStockGroupGoodsList as $item )
        {
            $currentGoods = current($item);
            $supplierCommodityType = $currentGoods['supplierCommodityType'];
            //重新合并每一个仓库商品
            $orderGoods = [];
            foreach ($item as $goods ) {
                $orderGoods = array_merge($orderGoods,$userGoodsList[$goods['skuCode']]);
                unset($goods);
            }

            //生成供应商主单号
            $supplierCode = $param['supplierGoodsInfo']['supplierCode'];
            $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
            $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
            //下游已申报，则使用下游的订单号作为中台子单号
            if( $isDelare && !$isShop && $supplierCommodityType != GOODS_TYPE_YBMY ) {
                $param['order']['supplier_dsn'] = $param['order']['orderSn'];
            } else {
                $param['order']['supplier_dsn'] = IdService::instance()->getOtherID();
            }

            $param['order']['goods'] = $orderGoods;
            $param['order']['isQueryExpress'] = 1;
            $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }

            $orderItems[] = $res['data'];
        }

        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }

    /**
     * 订单申报
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        return $this->callSdkApi(ShopWeiNiApiClient::class,$param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"获取成功");
    }

    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return $this->callSdkApi(ShopWeiNiApiClient::class,$param['apiBody'])->orderCancel($param);
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function orderExpress( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
   public function queryGoodsList( $param = [] )
   {
       //维妮只更新商品资料,所以直接根据供应商skuCode获取商品
       
       $res = $this->callSdkApi(ShopWeiNiApiClient::class,$param['apiBody'])->{__FUNCTION__}($param['queryBody']);
       if( $res['code'] != Normal::SUC ) {
           return $res;
       }
       return Normal::returnCode(Normal::SUC,"获取成功",[
           'total' => $res['data']['result']['TotalCount'],
           'list'  => $res['data']['result']['SkuList']
       ]);
   }

    /**
     * 商品列表查询接口(根据SKU)
     * @param array $param
     * @return mixed
     */
    public function queryGoodsListBySku( $param = [] )
    {
        $page=$param['queryBody']['page']??1;
        $limit=$param['queryBody']['limit']??30;
        //维妮只更新商品资料,所以直接根据供应商skuCode获取商品
        $goodsData=SupplierCommodity::instance()
            ->where('SupplierCompanyID',$param['queryBody']['supplierID'])
            ->orderBy('CreateTime')
            ->orderBy('ID')
            ->paginate($limit, ['SupplierCommoditySkuCode'], 'page', $page)->toArray();
        //没有数据就说明请求到最后一页
        if (empty($goodsData['data'])){
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'total' =>  $goodsData['total'],
                'list'  =>  []
            ]);
        }
        $param['queryBody']['skuNos']=array_column($goodsData['data'],'SupplierCommoditySkuCode');
        $res = $this->callSdkApi(ShopWeiNiApiClient::class,$param['apiBody'])->queryGoodsListBySkuNo($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total' => $goodsData['total'],
            'list'  => $res['data']
        ]);
    }




    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }

        $res = $this->callSdkApi(ShopWeiNiApiClient::class,$apiBody)->{__FUNCTION__}($orderInfo);
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }

        if( empty($res['data']) ) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }
        $ships       = $res['data'];
        // TRADE_STATUS_CONFIRM_WAIT,
        // TRADE_STATUS_DELIVERY_FINISHED
        $tradeStatus = array_column($ships,'TradeStatus');
        if(in_array('TRADE_STATUS_CONFIRM_WAIT', $tradeStatus)){
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }
        
        $ExpressName = implode(",", array_column($ships,'PostName'));
        $TrackingNo  = implode(",", array_column($ships,'PostNo'));
        
        if (empty($ExpressName) || empty($TrackingNo)){
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }
        return  Normal::returnCode(Normal::SUC,"已发货",[
            'expressInfo' => [
                'express_name'  => mb_strtoupper($ExpressName,'utf-8'),
                'express_sn'    => $TrackingNo,
            ]
        ]);
    }
}
